#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
WebSocket基础连接事件处理器
处理连接、断开、心跳等基础事件
"""

import time
from flask import request
from flask_socketio import emit
from core import extensions
from utils.session_manager import cleanup_client_sessions


def register_connection_events(socketio):
    """
    注册WebSocket连接相关事件
    
    Args:
        socketio: SocketIO实例
    """
    
    @socketio.on('connect')
    def handle_connect():
        """处理客户端连接"""
        print(f"🔌 WebSocket客户端连接: {request.sid}")
        extensions.connected_clients.add(request.sid)
        
        # 发送欢迎消息
        emit('status_update', {
            'type': 'connection',
            'message': 'WebSocket连接成功',
            'timestamp': int(time.time() * 1000),
            'client_id': request.sid
        })
        
        # 发送当前系统状态
        try:
            if extensions.voice_control_service:
                status = extensions.voice_control_service.get_status()
                emit('voice_control_status', {
                    'type': 'voice_status',
                    'data': status,
                    'timestamp': int(time.time() * 1000)
                })
        except Exception as e:
            print(f"❌ 发送初始状态失败: {e}")
    
    @socketio.on('disconnect')
    def handle_disconnect():
        """处理客户端断开连接"""
        print(f"🔌 WebSocket客户端断开: {request.sid}")
        cleanup_client_sessions(request.sid)
    
    @socketio.on('ping')
    def handle_ping(data=None):
        """处理心跳检测"""
        emit('pong', {'timestamp': int(time.time() * 1000)})
    
    @socketio.on('get_status')
    def handle_get_status(data=None):
        """处理获取状态请求"""
        try:
            status_data = {
                'backend_status': 'running',
                'voice_control_status': extensions.voice_control_service.get_status() if extensions.voice_control_service else None,
                'connected_clients': len(extensions.connected_clients),
                'timestamp': int(time.time() * 1000)
            }
            emit('status_response', status_data)
        except Exception as e:
            emit('error', {'message': f'获取状态失败: {str(e)}'})


def broadcast_to_all_clients(socketio, event, data):
    """
    向所有连接的客户端广播消息
    
    Args:
        socketio: SocketIO实例
        event: 事件名称
        data: 数据
    """
    if extensions.connected_clients:
        socketio.emit(event, data)
        print(f"📡 广播事件 {event} 到 {len(extensions.connected_clients)} 个客户端")

